<template>
    <div>
        <el-form :model="form" :rules="rules" ref="form">
            <el-form-item label="姓名" prop="id_name">
                <el-input v-model="form.id_name"></el-input>
            </el-form-item>
            <el-form-item label="身份证号" prop="id_no">
                <el-input v-model="form.id_no"></el-input>
            </el-form-item>
            <el-form-item>
                <div class="action-row">
                    <el-button type="primary" @click="submitForm">重置密码</el-button>
                    <div v-if="qrCodeDataUrl" class="qr-code">
                        <img width="100px" height="100px" :src="qrCodeDataUrl" alt="QR Code" />
                        <p class="qr-text"><span style="color:red">* </span>请扫描二维码,进行实名认证</p>
                    </div>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { uploadUserInfo } from '@/api/baidu'
import { authTokenStatus } from '@/api/token'
import QRCode from 'qrcode'
import { Loading } from 'element-ui'

export default {
    data() {
        return {
            form: {
                id_name: '',
                id_no: ''
            },
            rules: {
                id_name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' }
                ],
                id_no: [
                    { required: true, message: '请输入身份证号', trigger: 'blur' }
                ]
            },
            link: '',
            qrCodeDataUrl: '',
            token: '',
            intervalId: null, // 用于存储定时任务的 ID
            routerIntervalId: null
        }
    },
    created(){
        this.token='';
        this.qrCodeDataUrl = '';
    },
    methods: {
        submitForm() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    const loadingInstance = Loading.service({ fullscreen: true, text: "请稍等，正在生成二维码" })
                    uploadUserInfo(this.form)
                        .then(response => {
                            console.log('Response:', response)
                            if (response.code == 200) {
                                QRCode.toDataURL(response.data.baiduFaceAuthUrl)
                                    .then(url => {
                                        this.token = response.data.verify_token;
                                        this.qrCodeDataUrl = url
                                        this.startPolling() // 开始定时任务
                                    })
                                    .catch(err => {
                                        console.error('Error generating QR code:', err)
                                    });
                            } else {
                                this.$message.error(response.msg);
                            }
                        }).catch(error => {
                            console.error('request Error:', error)
                        }).finally(() => {
                            loadingInstance.close()
                        })
                } else {
                    console.log('表单验证失败')
                    return false
                }
            })
        },
        startPolling() {
            if (this.intervalId) {
                clearInterval(this.intervalId)
            }
            this.intervalId = setInterval(() => {
                this.pollBackend()
            }, 2000)
        },
        pollBackend() {
            // 调用后端接口
            console.log('Polling backend...')
            authTokenStatus({ token: this.token }).then(response => {
                if (response.code == 200 && response.data.realNameVerified == 1) {
                    //响应成功清除定时任务
                    this.stopPolling();
                    this.$message.success("实名认证成功，3秒后跳转密码重置页面");
                    this.routerIntervalId = setInterval(() => {
                        //跳转重置密码页面
                        this.$router.push('/reset-password');
                    }, 3000)

                }
            })
            // 这里调用你的后端接口
            // 例如：this.$post('/your-endpoint', { data: 'yourData' })
        },
        stopPolling() {
            if (this.intervalId) {
                clearInterval(this.intervalId)
                this.intervalId = null
            }
            if (this.routerIntervalId) {
                clearInterval(this.routerIntervalId)
                this.routerIntervalId = null
            }
            
        }
    },
    beforeDestroy() {
        this.stopPolling() // 在组件销毁前停止定时任务
    }
}
</script>

<style scoped>
.action-row {
    display: flex;
    align-items: center;
}

.qr-code {
    margin-left: 20px;
    /* 调整间距 */
    text-align: center;
    /* 使文字居中 */
}

.qr-text {
    width: 200px;
    margin-top: -25px;
    /* 去掉默认的 margin */
    padding: 0;
    /* 去掉默认的 padding */
    font-size: 14px;
    /* 可根据需要调整字体大小 */
}
</style>